package com.jxb.test20241216;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSum_1 {

    public static void main(String[] args) {
        System.out.println(Arrays.toString(hash(9)));
    }

    static int[] nums = {2,7,11,15};

    //暴力破解O(n^2)
    public static int[] brutalForce(int target) {
        int[] res = new int[2];
        for (int i = 0;i < nums.length;i++) {
            for (int j = 0;j < nums.length;j++) {
                if (nums[i]+nums[j] == target) {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return null;
    }

    //通过hash表来存储元素的值，减少时间复杂度，O(n)
    public static int[] hash(int target) {
        Map<Integer,Integer> map = new HashMap<>();
        int[] res = new int[2];
        for (int i = 0; i< nums.length; i++) {
            int other = target - nums[i];
            if (map.containsKey(other)) {
                res[0] = i;
                res[1] = map.get(other);
                return res;
            }else {
                map.put(nums[i],i);
            }
        }
        return res;
    }



}
